import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Switch, Select, message, Radio, InputNumber } from 'antd';
import PropTypes from 'prop-types';
const prefixCls = 'adapter-form';
import './index.less';
import * as API from '@api/system';
import ErroModal from '../erroModal/index';
import useClearTimeOut from '@components/hook/clear-time-out.js';
import cmdb from '@images/adapter/cmdb.png';
import { IP_V6, IP_RE, URL_RE } from '@util/constants';

const productDist = {
  cmdb: cmdb
};
const formItemLayout = {
  labelCol: {
    span: 5
  },
  wrapperCol: {
    span: 19
  }
};

const unitDict = [
  { value: 'hour', label: '时' },
  { value: 'day', label: '日' },
  { value: 'week', label: '周' },
  { value: 'month', label: '月' }
];

// eslint-disable-next-line react/prop-types
const AssetIdentificationForm = ({
  // eslint-disable-next-line react/prop-types
  onChange,
  visible,
  setVisible,
  form,
  detail,
  manufacturerList,
  setDetail,
  manufacturerFiledList
}) => {
  const addTimerCallBack = useClearTimeOut();
  const { getFieldDecorator, getFieldValue, validateFields, resetFields, setFieldsValue } = form;
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [errorVisbleText, setErroVisbleText] = useState();
  const [erroVisible, setErroVisble] = useState(false);

  const closeHandler = () => {
    setDetail();
    setVisible(false);
    resetFields();
  };

  const handleSubmit = () => {
    validateFields((err, values) => {
      if (err) {
        return;
      }
      if (values.updateCycle?.autoUpdate && !values.updateCycle?.value) {
        message.error('请填写数据更新时间！');
        return;
      }
      setConfirmLoading(true);
      let newValues = { ...values };
      detail ? (newValues.id = detail._id) : null;
      let api = !detail ? API.addAdapterList : API.editAdapterList;
      api({ ...newValues })
        .then(() => {
          message.success(!detail ? '新增成功' : '编辑成功');
          closeHandler();
          onChange();
        })
        .catch(({ type, message }) => {
          if (type === 'parsed') {
            setErroVisbleText(message);
          }
          setErroVisble(true);
        })
        .finally(() => {
          setConfirmLoading(false);
        });
    });
  };

  const validatorOpction = (rules, values, callback, type) => {
    if (!type) {
      callback();
    }
    switch (type) {
      case 'ip':
        if (!IP_V6.test(values) && !IP_RE.test(values) && !URL_RE.test(values)) {
          return callback('请输入正确的地址');
        }
        break;
      default:
    }
    callback();
  };

  useEffect(() => {
    if (detail) {
      const { adapterType, updateCycle } = detail;
      setFieldsValue({
        adapterType: adapterType,
        updateCycle: {
          autoUpdate: updateCycle?.autoUpdate
        }
      });
      addTimerCallBack(() => setFieldsValue(detail));
    } else {
      resetFields();
    }
  }, [visible]);

  // 变量切换的表单setFieldsValue会有异步问题，导致页面不显示
  const changeRadio = ({ target: { value } }) => {
    if (value) {
      addTimerCallBack(() =>
        setFieldsValue({
          updateCycle: {
            unit: 'day',
            value: 1
          }
        })
      );
    }
  };
  // 适配器配置表单
  const renderAdapterOpction = () => {
    let adapterType = getFieldValue('adapterType');
    return manufacturerFiledList?.[adapterType]?.map(item => {
      return (
        <Form.Item label={item.text} key={item.key}>
          {getFieldDecorator(`customData.${item.key}`, {
            rules: [
              {
                required: item.isOnly,
                message: `请输入${item.text}`
              },
              {
                validator: (rules, values, callback) =>
                  validatorOpction(rules, values, callback, item.validate)
              }
            ]
          })(<Input placeholder={`请输入${item.text}`} />)}
        </Form.Item>
      );
    });
  };

  return (
    <>
      <Modal
        title={`${detail ? '修改' : '添加'}适配器`}
        maskClosable={false}
        closable={true}
        width={500}
        onCancel={closeHandler}
        onOk={handleSubmit}
        visible={visible}
        className={prefixCls}
        confirmLoading={confirmLoading}
      >
        <Form {...formItemLayout}>
          <Form.Item label="适配器">
            {getFieldDecorator('adapterType', {
              rules: [
                {
                  required: true,
                  message: '请输入适配器名称'
                }
              ]
            })(
              <Select className="multi-select" placeholder="请选择适配器类型">
                {manufacturerList?.map((r, i) => {
                  return (
                    <Select.Option value={r.value} key={i}>
                      <img
                        src={productDist[r.value]}
                        width={72}
                        height={26}
                        style={{ paddingBottom: 5 }}
                      />
                      <span style={{ marginLeft: 10 }}>{r.text}</span>
                    </Select.Option>
                  );
                })}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="名称">
            {getFieldDecorator('name', {
              rules: [
                {
                  required: true,
                  message: '请输入名称'
                }
              ]
            })(<Input placeholder="请输入中文、英文或数字,字符长度2-32位" />)}
          </Form.Item>
          {renderAdapterOpction()}
          <Form.Item label="启用">
            {getFieldDecorator('enable', { valuePropName: 'checked', initialValue: true })(
              <Switch defaultChecked />
            )}
          </Form.Item>
          <Form.Item label="数据更新方式">
            {getFieldDecorator('updateCycle.autoUpdate', { initialValue: false })(
              <Radio.Group
                onChange={e => changeRadio(e)}
                style={{ marginRight: 0 }}
                options={[{ label: '单次', value: false }, { label: '周期', value: true }]}
              />
            )}
          </Form.Item>
          {getFieldValue('updateCycle.autoUpdate') === true && (
            <>
              <div className="df" style={{ marginLeft: 30 }}>
                <span className="form-label">数据更新:&nbsp;</span>
                <Form.Item>
                  {getFieldDecorator('updateCycle.value')(
                    <InputNumber
                      style={{ width: 140 }}
                      min={0}
                      onChange={value => {
                        let intervalTime = value;
                        if (intervalTime <= 1) {
                          intervalTime = 1;
                        } else {
                          intervalTime = Math.floor(intervalTime);
                        }
                        addTimerCallBack(() => {
                          setFieldsValue({
                            updateCycle: {
                              value: intervalTime
                            }
                          });
                        });
                      }}
                    />
                  )}
                </Form.Item>
                <Form.Item>
                  {getFieldDecorator('updateCycle.unit')(
                    <Select style={{ width: 80 }}>
                      {unitDict.map(r => (
                        <Select.Option key={r.value} value={r.value}>
                          {r.label}
                        </Select.Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>
              </div>
            </>
          )}
        </Form>
      </Modal>

      <ErroModal
        visible={erroVisible}
        setVisible={setErroVisble}
        errorVisbleText={errorVisbleText}
      />
    </>
  );
};

AssetIdentificationForm.propTypes = {
  visible: PropTypes.bool,
  setVisible: PropTypes.func,
  form: PropTypes.object,
  edit: PropTypes.bool,
  onChange: PropTypes.func,
  manufacturerList: PropTypes.array,
  detail: PropTypes.object,
  setDetail: PropTypes.array,
  manufacturerFiledList: PropTypes.array
};
export default Form.create({ name: 'AssetIdentificationForm' })(AssetIdentificationForm);
